package com.lxc.networkdemo

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.lxc.lib.net.http.HttpManager
import com.lxc.lib.net.http.RequestHelper
import com.lxc.networkdemo.apis.InfoApis
import com.lxc.networkdemo.databinding.ActivityMainBinding
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    private lateinit var binding: ActivityMainBinding

    val api = RequestHelper.getApi<InfoApis>(baseUrl = "http://wthrcdn.etouch.cn")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.run {
            btnB1.setOnClickListener {
                getData()
            }

            btnB3.setOnClickListener {
                startActivity(Intent(this@MainActivity, DemoActivity1::class.java))
            }
        }
    }

    private fun getData() {
        lifecycleScope.launch {
            val data = api.getDataForSuspendAsync("北京")
            HttpManager.formatResponse(data) {
                it.onSuccess {

                }.onFailure {

                }
            }
        }

        HttpManager.Builder(lifecycleScope).build().goJson(api.getDataForDeferredAsync("北京")) {
            if (it.status) {
                //success
                it.result?.data?.let { data ->
                    binding.tvData.text = data.toString()
                    Log.e(TAG, data.toString())
                }
            } else {
                //error
                Log.e(TAG, it.msg.toString())
            }
        }
    }

}